package com.unohacha.qqj.fzdr.main;

import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.adapter.NineGridViewClickAdapter2;
import com.unohacha.qqj.fzdr.bean.homebean.HomeAppCommentBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeSellerAreaListBean;
import com.unohacha.qqj.fzdr.common.utils.KeybordSUtils;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 讨论详情 item_comment_list2
 */
public class TalkDetailActivity2 extends BaseActivity implements OnRefreshLoadmoreListener {


    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.home1_title)
    LinearLayout home1Title;
    @BindView(R.id.car_list_recycler)
    RecyclerView carListRecycler;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    
    @BindView(R.id.comment_tv)
    EditText commentTv;
    @BindView(R.id.send_btn)
    TextView send_btn;
    
    private int supply_id;//记录ID
    private List<String> mContentList = new ArrayList<>();//评论的图片
    private List<HomeAppCommentBean.DataBeanX.DataBean> mCommentList = new ArrayList<>();
    private HomeSellerAreaListBean.DataBeanX.DataBean dataBean;
    private HomeAppCommentBean.DataBeanX.DataBean appDataBean;
    private int page = 1;
    private BaseRVAdapter mBaseAdapter;
    private String member_no;
    private String member_thumb;
    private String create_time;
    private String content;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_talk_detai2l;
    }

    @Override
    protected void initView() {
        super.initView();
        if (null != getIntent()) {
            supply_id = getIntent().getIntExtra("supply_id", 0);
            dataBean = (HomeSellerAreaListBean.DataBeanX.DataBean) getIntent().getSerializableExtra("data");
            Log.d("asdf",dataBean.getMember_no()+"//"+supply_id);
            appDataBean = new HomeAppCommentBean.DataBeanX.DataBean();
            if (null != dataBean){
                Log.d("asdf","sdfgsdfg");
                member_no = dataBean.getMember_no();
                member_thumb = dataBean.getMember_thumb();
                create_time = dataBean.getCreate_time();
                content = dataBean.getContent();
                
                appDataBean.setArticle_id(dataBean.getApp_cate_id());
                appDataBean.setContent(content);
                
                appDataBean.setCreate_time(create_time);
                appDataBean.setId(dataBean.getId());
                appDataBean.setMember_no(member_no);
                appDataBean.setMember_thumb(member_thumb);
                appDataBean.setReturn_list(dataBean.getList_pic_compress());
                mCommentList.add(0,appDataBean);
            }
        }
        commonTitle.setText(getResources().getString(R.string.talk_detail));
        commonRightImage.setVisibility(View.INVISIBLE);
        commonRightText.setVisibility(View.GONE);
        initRefreshLayout();
        getTalkDetailData(supply_id);
       
    }

    //评论
    private void isComment(int app_type,int typeid,int article_id,String pid,String content){
        Map<String,Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        params.put("app_type",app_type);//评价类型(1:展会信息;2:纺织学堂;3:商家讨论)
        params.put("typeid",typeid);//回复类型(1:添加评论;2:回复评论;3:回复再回复)
        params.put("article_id",article_id);
        params.put("pid",pid);
        params.put("content",content);
        Log.d("article_id",article_id+"..");
        XUtil.Post(UrlConfig.COMMENTS_APP_ADD,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("TAG: isComment",result.toString());
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")){
                        if (KeybordSUtils.isSoftInputShow(TalkDetailActivity2.this)){
                            KeybordSUtils.closeKeybord(commentTv,TalkDetailActivity2.this);
                            commentTv.setText("");
                        }
                        page = 1;
                        getTalkDetailData(supply_id);
                    }else if (100 == jsonObject.optInt("code")){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }
                    MyToast(jsonObject.optString("message"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }
    
    private void initRefreshLayout() {
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        carListRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        carListRecycler.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
    }

    @OnClick({R.id.common_back,R.id.send_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;
            case R.id.send_btn://评论
                if (!TextUtils.isEmpty(commentTv.getText().toString().trim())){
                    isComment(3,1,supply_id,"",commentTv.getText().toString().trim());
                }else {
                    MyToast("请输入搜索内容!");
                    return;
                }
                break;
        }
    }

    //获取讨论详情数据 HomeAppCommentBean
    private void getTalkDetailData(int article_id) {
        showLoading();
        Map<String, Object> params = new HashMap<>();
        params.put("app_type", 3);//评价类型(1:展会信息;2:纺织学堂;3:商家讨论)
        params.put("article_id",article_id);
        params.put("page",page);
        Log.d("article_id",article_id+"...");

        XUtil.Post(UrlConfig.APP_COMMENTS_LIST, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("TAG: getTalkDetailData", result);
               
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    Log.d("artical_id",jsonObject.optInt("code")+"//");

                    if (1 == jsonObject.optInt("code")) {
                        Gson gson = new Gson();
                        HomeAppCommentBean commentBean = gson.fromJson(result,HomeAppCommentBean.class);
                        if (null != commentBean){
                            if (page == 1) {
                                if (mCommentList.size() >= 2){
                                    mCommentList.clear();
                                    mCommentList.add(0,appDataBean);

                                }
                                mCommentList.addAll(commentBean.getData().getData());
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.resetNoMoreData();
                            }else {
                                mRefreshLayout.finishLoadmore();
                                mBaseAdapter.notifyDataSetChanged();
                            }
                           
                            setContentListAdapter();
                           
                        }
                    } else if (100 == jsonObject.optInt("code")) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();  
                    }else {
                        if (page == 1){
                            MyToast(jsonObject.optString("message"));
                            if (null != mCommentList){
//                                mCommentList.clear();
                                setContentListAdapter();
                            }

                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                            mBaseAdapter.notifyDataSetChanged();
                        }else {
                            MyToast(getResources().getString(R.string.no_more_data));
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                        }
                    }
                } catch (JSONException e) {
                    
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                hideLoading();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                hideLoading();
            }
        });
    }
    
    //设置评论图片
    private void setContentListAdapter() {
        Log.d("asdf",mCommentList.size()+"//");
        mBaseAdapter = new BaseRVAdapter(this,mCommentList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_comment_list2;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                if (null != mCommentList){
                    ImageView store_pic = holder.getImageView(R.id.store_pic);
                    TextView user_name_tv = holder.getTextView(R.id.user_name_tv);
                    TextView user_report_content = holder.getTextView(R.id.user_report_content);
                    TextView comment_user = holder.getTextView(R.id.comment_user);
                    RecyclerView comment_rv = holder.getView(R.id.comment_rv);
                    View view_divider = holder.getView(R.id.view_divider);
                    TextView comment_content = holder.getTextView(R.id.comment_content);
                    if (position == 0){
                        view_divider.setVisibility(View.VISIBLE);
                        comment_content.setVisibility(View.VISIBLE);
                        comment_content.setText(dataBean.getTitle());
                    }else {
                        view_divider.setVisibility(View.GONE);
                        comment_content.setVisibility(View.GONE);
                    }
                    
                    Glide.with(TalkDetailActivity2.this).load(mCommentList.get(position).getMember_thumb())
                            .error(R.drawable.ic_default_photo).into(store_pic);
                    user_name_tv.setText(mCommentList.get(position).getMember_no());
                    user_report_content.setText(mCommentList.get(position).getCreate_time());
                    comment_user.setText(mCommentList.get(position).getContent());
//                    comment_rv.setLayoutManager(new GridLayoutManager(TalkDetailActivity2.this,3,LinearLayoutManager.VERTICAL,false));
                    if (0 != mContentList.size()){
                        mContentList.clear();
                    }
                    mContentList.addAll(mCommentList.get(position).getReturn_list());

                    if (0 != mContentList.size()) {

                        ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                        List<String> imageDetails = mCommentList.get(position).getReturn_list();
                        if (imageDetails != null) {
                            for (String imageDetail : imageDetails) {
                                ImageInfo info = new ImageInfo();
                                info.setThumbnailUrl(imageDetail);
                                info.setBigImageUrl(imageDetail);
                                imageInfo.add(info);
                            }
                        }
                        NineGridView mRecyclerView = holder.getView(R.id.mRecyclerView);//图片的列表 3 列
                        mRecyclerView.setSingleImageSize(300);
                        
                        mRecyclerView.setAdapter(new NineGridViewClickAdapter2(mContext, imageInfo));
//                        BaseRVAdapter mCommentAdapter = new BaseRVAdapter(TalkDetailActivity2.this,mContentList) {
//                            @Override
//                            public int getLayoutId(int viewType) {
//                                return R.layout.item_find_pic2;
//                            }
//    
//                            @Override
//                            public void onBind(BaseViewHolder holder, int position) {
//                                ImageView find_pic_iv= holder.getImageView(R.id.find_pic_iv);
//                                    Glide.with(TalkDetailActivity2.this).
//                                            load(mContentList.get(position)).into(find_pic_iv);
//                            }
//                        };
//                        mCommentAdapter.addItemClickListener(new OnItemClickListener() {
//                            @Override
//                            public void itemSelect(int position) {
//                                if (0 != mContentList.size()) {
//                                    //点击查看大图
//                                    Intent intent = new Intent(
//                                            TalkDetailActivity2.this, LookBigPicActivity.class);
//                                    intent.putExtra("imgUrl", mContentList.get(position));
//                                    intent.putExtra("listData", mContentList.get(position));
//                                    intent.putExtra("type", "4");
//                                    startActivity(intent);
//                                }
//                            }
//                        });
//                        comment_rv.setAdapter(mCommentAdapter);
//                        mCommentAdapter.notifyDataSetChanged();
                    }

                }
            }
        };
        carListRecycler.setAdapter(mBaseAdapter);
    }
    
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                getTalkDetailData(supply_id);
            }
        }, 2000);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page ++;
                getTalkDetailData(supply_id);
            }
        }, 2000);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

  
}
